package com.mail.manager.modular.controller.portal;

import com.alibaba.fastjson.JSONObject;
import com.mail.manager.common.annotion.Permission;
import com.mail.manager.common.constant.Const;
import com.mail.manager.common.constant.tips.Tip;
import com.mail.manager.common.controller.BaseController;
import com.mail.manager.common.exception.BizExceptionEnum;
import com.mail.manager.common.exception.BussinessException;
import com.mail.manager.config.properties.GunsProperties;
import com.mail.manager.core.shiro.ShiroKit;
import com.mail.manager.core.util.DateUtil;
import com.mail.manager.core.util.ToolUtil;
import com.mail.manager.modular.model.Product;
import com.mail.manager.modular.model.ProductCategory;
import com.mail.manager.modular.service.portal.IProductCategoryService;
import com.mail.manager.modular.service.portal.IProductService;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.naming.NoPermissionException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 创建人： Shi Heng
 * 创建时间：2018-04-03 18:06
 * QQ：374696376
 * Description：产品控制器
 */
@Controller
@RequestMapping("/portal/product")
public class ProductController extends BaseController {

    @Resource
    private GunsProperties gunsProperties;

    @Resource
    IProductService productService;
    @Resource
    IProductCategoryService productCategoryService;

    private static String PREFIX = "/portal/product/";

    /**
     * 跳转到查看管理员列表的页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "product.html";
    }

    /**
     * 跳转到查看管理员列表的页面
     */
    @RequestMapping("/product_add")
    public String addView() {
        return PREFIX + "product_add.html";
    }

    /**
     * 跳转到编辑管理员页面
     */
    @Permission
    @RequestMapping("/product_edit/{productId}")
    public String productEdit(@PathVariable Integer productId, Model model) {
        if (ToolUtil.isEmpty(productId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Product product = productService.selectByPrimaryKey(productId);
        ProductCategory category = productCategoryService.selectByPrimaryKey(product.getProduct_category_id());
        model.addAttribute("cateGoryName", category.getSimple_name());
        model.addAttribute(product);
        return PREFIX + "product_edit.html";
    }

    /**
     * 跳转到查看用户详情页面
     */
    @RequestMapping("/product_info")
    public String productInfo(Model model) {
        Integer productId = ShiroKit.getUser().getId();
        if (ToolUtil.isEmpty(productId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Product product = productService.selectByPrimaryKey(productId);
        model.addAttribute(product);
        return PREFIX + "product_view.html";
    }


    /**
     * 查询管理员列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String title, @RequestParam(required = false) String beginTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) Integer product_category_id) {
        List<Map<String, Object>> products = productService.selectProducts(title, beginTime, endTime, product_category_id);
        return products;
    }

    /**
     * 添加管理员
     */
    @RequestMapping("/add")
    @ResponseBody
    public Tip add(Product product, BindingResult result) {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        product.setCreate_time(DateUtil.parseTime(DateUtil.getTime()));
        String description = product.getDescription()
                .replaceAll("& lt;", "<")
                .replaceAll("& gt;", ">");
        product.setDescription(description);
        productService.insert(product);
        return SUCCESS_TIP;
    }

    /**
     * 修改管理员
     *
     * @throws NoPermissionException
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Tip edit(Product product, BindingResult result) throws NoPermissionException {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String description = product.getDescription()
                .replaceAll("& lt;", "<")
                .replaceAll("& gt;", ">");
        product.setDescription(description);
        productService.updateObjtById(product);
        return SUCCESS_TIP;
    }


    /**
     * 修改产品
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Product product) {
        if (ToolUtil.isEmpty(product) || product.getId() == null) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String description = product.getDescription()
                .replaceAll("& lt;", "<")
                .replaceAll("& gt;", ">");
        product.setDescription(description);
        productService.updateObjtById(product);
        return super.SUCCESS_TIP;
    }


    /**
     * 删除管理员（逻辑删除）
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Tip delete(@RequestParam Integer productId) {
        productService.delteObject(productId);
        return SUCCESS_TIP;
    }

    /**
     * 查看管理员详情
     */
    @RequestMapping("/view/{productId}")
    @ResponseBody
    public Product view(@PathVariable Integer productId) {
        if (ToolUtil.isEmpty(productId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return productService.selectByPrimaryKey(productId);
    }

    /**
     * https://www.cnblogs.com/DarrenChan/p/6892214.html?utm_source=itdadao&utm_medium=referral
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public JSONObject upload(@RequestPart("file") MultipartFile picture) {
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        JSONObject result = new JSONObject();
        String path = gunsProperties.getFileUploadPath()+"/product/" + pictureName;
        Client client = new Client();
        WebResource resource = client.resource(path);
        try {
            resource.put(String.class, picture.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        result.put("errno", 0);
        result.put("data", path);
        return result;
    }


}
